$('[data-rel=popover]').popover({container:'body'});
laydate.render({
    elem: 'input[name=sign_at]',
    type: 'datetime',
    done:function(value, data){
        $('input[name=sign_at]').closest('.form-group').find('.help-block.error').remove()
    }
})
laydate.render({
    elem: 'input[name=start_over_at]',
    type: 'date',
    range: true,
})
var tableContainer = $('#customer-list-table')
var tableSearchForm = '.customer-list-table-search form'
$(document).on('show.bs.modal', '#customer-table-modal', function(e) {
    initCustomersTable()
})
function refreshCustomerTable() {
    tableContainer.bootstrapTable('refresh', {
        query: ace.form.serialize(tableSearchForm)
    })
}
function initCustomersTable () {
    tableContainer.bootstrapTable('destroy');
    var columns = [
        {radio: true},
        {title: '客户单位', field: 'unit'},
        {title: '地区', field: 'pcc'},
        {title: '级别', field: 'level_msg'},
        {title: '联系人', field: 'realname'},
        {title: '联系电话', field: 'mobile'},
    ]
    tableContainer.bootstrapTable({
        url: '/contract/customers',
        uniqueId: "id",
        striped: true,
        toolbar: '#toolbar',
        pagination: true,
        sidePagination: "server",
        paginationDetailHAlign:' hidden',
        pageSize: 10,
        columns: columns,
        queryParams: function (params) {
            return $.extend({}, params, ace.form.serialize(tableSearchForm))
        },
        onCheck: function (row) {
            $('input[name=uid]').val(row.id)
            $('#customer-input').val(row.unit + '（' + row.pcc +'）')
            $('#customer-table-modal').modal('hide')
            $('#customer-input').closest('.form-group').find('.help-block.error').remove()
        }
    });
}

function addMaterial() {
    $('#material-list tbody').append($('#material-item-tpl').html())
    $('.material-empty').hide()
}
$(document).on('click', '.remove-material', function () {
    $(this).closest('.material-item').remove()
    if ($(document).find('.material-item').length == 0) {
        $('.material-empty').show()
    }
})
function renderContractFormError(error, ele) {
    var $fromGroup = ele.closest('.form-group')
    if (ele.attr('name') == 'product_extra_amount[]') {
        if ($fromGroup.find('.error-box').length > 0) {
            $fromGroup.find('.error-box').html(error)
        } else {
            error.appendTo($fromGroup)
        }
    } else {
        if ($fromGroup.find('.error-box').length > 0) {
            $fromGroup.find('.error-box').html(error)
        } else {
            error.appendTo($fromGroup.children('div'))
        }
    }
}

var contractAttachmentUploader = WebUploader.create({
    server: '/upload',
    pick: '#attchmentPicker',
    resize: false,
    duplicate: true,
    auto: true,
    formData: {
        file_key: 'contract_attachment'
    },
})
contractAttachmentUploader.on('uploadSuccess', function (file, res) {
    console.log(file)
    if (res.code == 0) {
        $('#contract-attachment-list').append('<li><input type="hidden" name="attachment[]" value="'+res.data.filepath+'"><input type="hidden" name="attachment_name[]" value="'+file.name+'"><a href="/'+res.data.filepath+'" target="_blank">'+file.name+'</a> <button class="btn btn-link" onclick="$(this).parent().remove()"><i class="fa fa-remove red"></i></button></li>')
    } else {
        ace.alert.err(res.msg);
    }
})


$.validator.addMethod("money", function(value, element) {
    return this.optional(element) || /^((0)|(0\.0[1-9])|(0\.[1-9]\d?)|([1-9]\d*\.\d{1,4})|([1-9]\d*))$/.test(value);
}, "必须输入合法的金额，最多保留四位小数");
$('#contractForm').validate({
    errorElement: 'div',
    focusInvalid: false,
    errorClass: 'help-block error',
    ignore: "",
    rules: {
        code: {required: true},
        uid: {required: true},
        sign_at: {required: true},
        total_fee: {money: true},
        product_amount: {digits: true},
        'product_extra_amount[]': {digits: true},
    },
    messages: {
        code: {required: '合同编号不能为空'},
        uid: {required: '采购方必须选择'},
        sign_at: {required: '签约时间不能为空'},
        product_amount: {digits: '数量输入不正确'},
        'product_extra_amount[]': {digits: '数量输入不正确'},
    },
    highlight: function (e) {
        $(e).closest('.form-group').removeClass('has-info');
    },
    success: function (e) {
        $(e).remove();
    },
    errorPlacement: function (error, ele) {
        renderContractFormError(error, ele)
    },
    submitHandler: function(form) {
        $(form).ajaxSubmit({
            dataType : "json",
            success: function(res) {
                if (res.code==0) {
                    ace.alert.ok('保存成功', function(){
                        window.location.href = '/contract/index';
                    });
                }else{
                    if (res.errors) {
                        for (let key in errors) {
                            renderContractFormError($('<div class="help-block error">' + errors[key][0] + '</div>'), $('[name=' + key + ']'))
                        }
                    }
                    ace.alert.err(res.msg);
                }
            },
            error: function(xhr, status, error) {
                if(status==='error') ace.alert.err('服务器错误');
            }
        });
    }
})
